package com.huanshi.security.config;


import com.huanshi.utils.JwtTokenUtil;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {


  @Override
  protected void doFilterInternal(@NonNull HttpServletRequest request,
                                  @NonNull HttpServletResponse response,
                                  @NonNull FilterChain filterChain) throws ServletException, IOException {
//    if (request.getServletPath().contains("/api/usm/auth")) {
//      filterChain.doFilter(request, response);
//      return;
//    }
    //检查是否有passtoken注释，有则跳过认证

    final String authHeader = request.getHeader("Authorization");
    if (authHeader == null ||!authHeader.startsWith("Bearer ")) {
      filterChain.doFilter(request, response);
      return;
    }
    String token = authHeader.substring(7);
    UsernamePasswordAuthenticationToken authentication = getAuthentication(token);
    SecurityContextHolder.getContext().setAuthentication(authentication);
    filterChain.doFilter(request, response);
  }

  private UsernamePasswordAuthenticationToken getAuthentication(String token) {

    if (token != null) {
      Claims claims = JwtTokenUtil.parseJWT(token);
      String user  = claims.getSubject();
      @SuppressWarnings("unchecked")
      List<String> roles = claims.get("role", List.class);
      List<SimpleGrantedAuthority> auth = roles.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());

      if (user != null) {
        return new UsernamePasswordAuthenticationToken(user, null, auth);
      }
      return null;
    }
    return null;
  }
}
